<template>
  <div style="margin-top: 40px">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      :disabled="readOnly"
    >
      <el-form-item v-show="false" label="id：" prop="id">
        <el-input v-model="ruleForm.id" />
      </el-form-item>
      <el-form-item label="姓名：" prop="username">
        <el-input v-model="ruleForm.username" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别：" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio label="男" />
          <el-radio label="女" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="QQ邮箱：" prop="email">
        <el-input v-model="ruleForm.email" />
      </el-form-item>
      <el-form-item label="电话：" prop="phone">
        <el-input v-model="ruleForm.phone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="店铺名称：" prop="shopName">
        <el-input v-model="ruleForm.shopName" placeholder="请输入店铺名称" />
      </el-form-item>
      <el-form-item label="店铺地址：" prop="shopAddress">
        <el-input v-model="ruleForm.shopAddress" placeholder="请输入店铺名称" />
      </el-form-item>
      <el-form-item label="店铺logo：" prop="shopLogo">
        <el-upload
          class="avatar-uploader"
          :action="this.action"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="shopLogoImage" :src="shopLogoImage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <div slot="tip" class="el-upload__tip">只能上传jpeg、jpg、png、gif文件，且不超过2M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="菜单二维码：" prop="qrUrl">
        <el-button size="small" type="primary" @click="generateQRCode">生成二维码</el-button>
        <img v-if="QRUrlImage" :src="QRUrlImage" class="avatar">
      </el-form-item>
    </el-form>
    <div align="center">
      <el-button @click="readOnly?handleEdit():handleSave()">{{ readOnly?'编辑':'保存' }}</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </div>

</template>

<script>
import axios from 'axios'
import { getWbeRoot, getFileRoot } from '../../api/web-site'
import sessionStorage from '../../assets/js/storage'

export default {
  name: 'BusinessDetails',

  data () {
    /*
    * 手机号校验
    * */
    const checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }

    return {
      /* 商家id */
      id: '',

      ruleForm: {
        id: '',
        username: '',
        sex: '',
        email: '',
        phone: '',
        shopLogo: '',
        shopName: '',
        shopAddress: '',
        qrUrl: ''
      },

      readOnly: '',

      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入QQ邮箱', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        shopName: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ],
        shopAddress: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      },

      /* 上传图片接口图片地址 */
      action: getWbeRoot() + '/api/upload/myUpload',
      /* 店铺头像地址 */
      shopLogoImage: '',

      /* 菜单二维码图片地址 */
      QRUrlImage: ''
    }
  },

  created () {
    this.id = sessionStorage.getItem('id')
    this.readOnly = sessionStorage.getItem('type') === 'view'
    this.getFormData(this.id)
  },

  methods: {

    /**
     * 商家详情请求
     * @param val
     */
    getFormData (val) {
      axios.get(getWbeRoot() + '/api/sysUser/getUserById', {
        params: {
          userId: val
        }
      }).then(
        response => {
          if (response.status === 200) {
            this.ruleForm = response.data
            this.shopLogoImage = getFileRoot() + response.data.shopLogo
            if (response.data.qrUrl !== '' && response.data.qrUrl !== null) {
              this.QRUrlImage = getFileRoot() + response.data.qrUrl
            }
          }
        }
      )
    },

    /**
     * 返回
     */
    back () {
      this.$router.push('business-manage')
    },

    /**
     * 编辑按钮
     */
    handleEdit () {
      this.readOnly = false
    },

    /**
     * 修改保存
     */
    handleSave () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          axios.post(getWbeRoot() + '/api/sysUser/updateSysUser', this.ruleForm
          ).then(
            response => {
              if (response.status === 200) {
                this.$message({
                  showClose: true,
                  message: '操作成功',
                  type: 'success'
                })
                this.$router.push('business-manage')
              }
            }
          )
        } else {
          return false
        }
      })
    },

    /**
     * 手机号校验
     * @param val
     */
    isCellPhone (val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },

    /**
     * 图片上传
     * @param res
     * @param file
     */
    handleAvatarSuccess (res, file) {
      if (res.code === '200') {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success'
        })
        this.shopLogoImage = URL.createObjectURL(file.raw)
        this.ruleForm.shopLogo = res.data
      } else {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传jpeg、jpg、png、gif格式的图片')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    /**
     * 生成二维码
     */
    generateQRCode () {
      axios.get(getWbeRoot() + '/api/sysUser/setQRCode', {
        params: {
          userId: this.id
        }
      }).then(
        response => {
          if (response.data.code === '200') {
            this.ruleForm.qrUrl = response.data.data
            this.QRUrlImage = getFileRoot() + response.data.data
            this.$message({
              showClose: true,
              message: response.data.msg,
              type: 'success'
            })
          } else {
            this.$message({
              showClose: true,
              message: '生成失败',
              type: 'info'
            })
          }
        }
      )
    }

  }

}
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
